'use strict';
export default {
  addHook: addHook,
  bootstrapMpa : bootstrapMpa,
  bootstrapSpaReact: bootstrapSpaReact,
  bootstrapSpaVue : bootstrapSpaVue,
  init : init,
  removeHook : removeHook,
  report : report,
  reportError :reportError,
  reportExt : reportExt,
  setAppInfo : setAppInfo,
  setDeviceInfo : setDeviceInfo,
  setFreeRouteMode : setFreeRouteMode,
  setNativeProxyMode : setNativeProxyMode,
  setUserInfo : setUserInfo,
  startContinuesReport : startContinuesReport,
  stopContinuesReport : stopContinuesReport
}
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
function _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); }
function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }


/**
 * Copyright (c) 2022-2024，云海链控股股份有限公司.
 */

/**
 * This file contains polyfills.
 *
 * @since 1.0.0
 * @author Yiming Luo
 */

navigator.sayswho = function () {
  var ua = navigator.userAgent;
  var tem = '',
    // eslint-disable-next-line id-length
    M = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
  if (/trident/i.test(M[1])) {
    tem = /\brv[ :]+(\d+)/g.exec(ua) || [];
    return "IE ".concat(tem[1] || '');
  }
  if (M[1] === 'Chrome') {
    tem = ua.match(/\b(OPR|Edge?)\/(\d+)/);
    if (tem !== null) {
      return tem.slice(1).join(' ').replace('OPR', 'Opera').replace('Edg ', 'Edge ');
    }
  }
  M = M[2] ? [M[1], M[2]] : [navigator.appName, navigator.appVersion, '-?'];
  if ((tem = ua.match(/version\/(\d+)/i)) !== null) {
    M.splice(1, 1, tem[1]);
  }
  return M.join(' ');
}();
navigator.sayswhere = function () {
  var ua = navigator.userAgent;

  // Android
  if (/(Android|Adr)/.test(ua)) {
    return 1;
  }

  // iOS
  if (/\(i[^;]+;( U;)? CPU.+Mac OS X/.test(ua)) {
    return 2;
  }

  // unknown
  return -1;
}();
(function () {
  if (typeof Object.assign !== 'function') {
    Object.assign = function (target) {
      if (target === undefined || target === null) {
        throw new TypeError('Cannot convert undefined or null to object');
      }
      var output = Object(target);
      for (var index = 1; index < arguments.length; index++) {
        var source = arguments[index];
        if (source !== undefined && source !== null) {
          for (var nextKey in source) {
            // eslint-disable-next-line max-depth
            if (source.hasOwnProperty(nextKey)) {
              output[nextKey] = source[nextKey];
            }
          }
        }
      }
      return output;
    };
  }
})();

/**
 * Copyright (c) 2022-2024，云海链控股股份有限公司.
 */

/**
 * This file contains common utilities.
 *
 * @since 1.0.0
 * @author Yiming Luo
 */

/** cookie part */

function removeCookie(name) {
  sessionStorage.removeItem(name);
  sessionStorage.removeItem("".concat(name, "_ttl"));
}
function getCookie(name) {
  var ttl = sessionStorage.getItem("".concat(name, "_ttl"));
  if (ttl) {
    if (ttl >= Date.now()) {
      return sessionStorage.getItem(name);
    }
    removeCookie(name);
  }
  return null;
}
function setCookie(name, value) {
  var hour = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;
  sessionStorage.setItem(name, value);
  sessionStorage.setItem("".concat(name, "_ttl"), hour * 60 * 60 * 1000 + Date.now());
}

/** generator part */

function generateGuid() {
  var S4 = function S4() {
    return ((1 + Math.random()) * 0x10000 | 0).toString(16).substring(1);
  };
  return "".concat(S4() + S4(), "-").concat(S4(), "-").concat(S4(), "-").concat(S4(), "-").concat(S4()).concat(S4()).concat(S4());
}

/** type part */

function isType(value, typeName) {
  if (!typeName) {
    return false;
  }
  var type = Object.prototype.toString.call(value);
  return type.match(/^\[object (.*?)]$/)[1].toLowerCase() === typeName;
}
function isEmpty(value) {
  return value === null || value === undefined;
}
function isBlank(value) {
  return isEmpty(value) || value === '';
}
function isObject(value) {
  return isType(value, 'object');
}
function isArray(value) {
  return isType(value, 'array');
}
function isNumber(value) {
  return isType(value, 'number');
}
function isFunction(value) {
  return isType(value, 'function');
}

/**
 * Copyright (c) 2022-2024，云海链控股股份有限公司.
 */

function parseUri(uri) {
  uri = uri || location.href;
  if (!isBlank(uri) && uri.indexOf('?') > -1) {
    return uri.substring(0, uri.indexOf('?'));
  }
  return uri;
}
function parseQueryParams() {
  var qs = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
  if (isBlank(qs)) {
    qs = location.search.length > 0 ? location.search.substring(1) : '';
  } else {
    qs = qs.substring(qs.indexOf('?') + 1);
  }
  var items = qs.length ? qs.split('&') : [];
  var params = {};
  var name = null;
  var value = null;
  items.forEach(function (item) {
    var itemPair = item.split('=');
    name = decodeURIComponent(itemPair[0]);
    value = decodeURIComponent(itemPair[1]);
    if (!isBlank(name)) {
      params[name] = value;
    }
  });
  return params;
}
function request(type) {
  var serializer = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : function (params) {
    return params;
  };
  return function (url, params, callback, headers, timeout) {
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function () {
      if (xhr.readyState === 4) {
        if (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) {
          if (isFunction(callback)) {
            callback(xhr.responseText);
          }
        }
      }
    };
    xhr.open(type, url, true);
    if (isObject(headers)) {
      for (var header in headers) {
        if (headers.hasOwnProperty(header)) {
          xhr.setRequestHeader(header, headers[header]);
        }
      }
    }
    xhr.ontimeout = function () {
      if (isFunction(timeout)) {
        timeout();
      }
    };
    xhr.send(params ? serializer(params) : null);
  };
}
function postRequestInJson(url, params, callback, headers, timeout) {
  request('POST', function (params) {
    return JSON.stringify(params);
  })(url, params, callback, Object.assign(headers || {}, {
    'Content-Type': 'application/json'
  }), timeout);
}

/**
 * Copyright (c) 2022-2024，云海链控股股份有限公司.
 */

var Registry = {
  config: {
    appKey: null,
    appVersion: '0.0.1',
    userKey: null,
    clientId: null,
    subscribeId: null,
    enableProxy: false,
    enableFreeRoute: false,
    freeRouteIncludeParams: false,
    freeRouteExcludeParams: false,
    hooks: {},
    globalHooks: {}
  },
  context: {}
};
function setConfigValue(key, value) {
  Registry.config[key] = value;
}
function getConfigValue(key) {
  return Registry.config[key];
}
function setContextValue(key, value) {
  Registry.context[key] = value;
}
function getAllContext() {
  return Object.assign({}, Registry.context);
}

/**
 * Copyright (c) 2022-2024，云海链控股股份有限公司.
 */

function checkNamespace(namespace) {
  if (!namespace) {
    throw new Error('namespace is required');
  }
}
function checkAppKey(appKey) {
  if (!appKey) {
    throw new Error('appKey is required');
  }
}
function checkAppVersion(appVersion) {
  if (!appVersion) {
    throw new Error('appVersion is required');
  }
}
function checkUserKey(userKey) {
  if (!userKey) {
    throw new Error('userKey is required');
  }
}
function checkEventKey(eventKey) {
  if (!eventKey) {
    throw new Error('eventKey is required');
  }
}
function checkHookKey(hookKey) {
  var readonly = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
  if (!hookKey) {
    throw new Error('hookKey is required');
  }
  if (readonly) {
    return;
  }
  if (getConfigValue('hooks').hasOwnProperty(hookKey) || getConfigValue('globalHooks').hasOwnProperty(hookKey)) {
    throw new Error('hookKey is existed');
  }
}
function checkCallback(callback) {
  if (!callback) {
    throw new Error('callback is required');
  }
  if (!isFunction(callback)) {
    throw new Error('callback must be a function');
  }
}
function checkConfig(config) {
  if (!isObject(config)) {
    throw new Error('config must be an object');
  }
}

/**
 * Copyright (c) 2022-2024，云海链控股股份有限公司.
 */

// Sinldo webview context
var CONTAINER_SINLDO = 'Sinldo';
// Yxcz webview context
var CONTAINER_YXCZ = 'Yxcz';

/**
 * register callback function to global for native calling.
 *
 * @param {String} globalFunName function name
 * @param {Function} callback callback function
 * @param {*} context binding context
 */
function registerCallback(globalFunName, callback, context) {
  if (globalFunName && callback) {
    window[globalFunName] = callback.bind(context || this);
  }
}

/**
 * invoke native function.
 *
 * @param {String} nativeFunName native function name
 * @param {*} params report data
 * @param {String} globalFunName callback function name
 */
function invokeNative(nativeFunName, params, globalFunName) {
  if (isObject(params)) {
    params = JSON.stringify(params);
  }
  if (navigator.sayswhere === 1) {
    try {
      window[CONTAINER_YXCZ].callNative(nativeFunName, params, globalFunName);
    } catch (ignore) {
      window[CONTAINER_SINLDO].callNative(nativeFunName, params, globalFunName);
    }
  } else if (navigator.sayswhere === 2) {
    try {
      window.webkit.messageHandlers[CONTAINER_SINLDO].postMessage([nativeFunName, params, globalFunName]);
    } catch (ignore) {
      window.webkit.messageHandlers[CONTAINER_YXCZ].postMessage([nativeFunName, params, globalFunName]);
    }
  } else {
    throw new Error("platform don't support native function: ".concat(nativeFunName));
  }
}

/**
 * generate native invoke function.
 *
 * @param {String} nativeFunName native function name
 * @param {String} globalFunName callback function name
 * @returns {Function} nativeInvoke function
 */
function generateNativeInvoke(nativeFunName, globalFunName) {
  if (!globalFunName) {
    globalFunName = nativeFunName;
  }
  return function (params, callback, context) {
    registerCallback(globalFunName, callback, context);
    invokeNative(nativeFunName, params, globalFunName);
  };
}

/**
 * generate xhr invoke function.
 *
 * @param {String} url restful url
 * @returns {Function} http request function
 */
function generateWebInvoke(url) {
  var appId = getConfigValue('subscribeId');
  var clientId = getConfigValue('clientId');
  return function () {
    var params = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    var callback = arguments.length > 1 ? arguments[1] : undefined;
    postRequestInJson(url, params, callback, {
      appId: appId,
      clientId: clientId
    });
  };
}

/**
 * Copyright (c) 2022-2024，云海链控股股份有限公司.
 */

// user log harvest endpoint
var REPORT_API = 'https://content-middle-web-dev.ssc-hn.com/api/log-beat/harvest/log/V1';
// online user status endpoint
var REPORT_ERROR_API = 'https://content-middle-web-dev.ssc-hn.com/api/log-beat/harvest/crash/log/V1';

/**
 * generate final report data with original report data:
 *  check required fields and filling default values.
 *  using hooks to process the report data.
 *
 * @param {*} params original report data
 * @param {Array<Function>} hooks report hooks
 * @returns {*} final report data
 */
function generateFullParams() {
  var params = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  var hooks = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
  checkConfig(params);
  checkEventKey(params.eventKey);
  if (!params.hasOwnProperty('namespace') || isEmpty(params['namespace'])) {
    params['namespace'] = getConfigValue('namespace');
    checkAppKey(params['namespace']);
  }
  if (!params.hasOwnProperty('appKey') || isEmpty(params['appKey'])) {
    params['appKey'] = getConfigValue('appKey');
    checkAppKey(params['appKey']);
  }
  if (!params.hasOwnProperty('appVersion') || isEmpty(params['appVersion'])) {
    params['appVersion'] = getConfigValue('appVersion');
    checkAppVersion(params['appVersion']);
  }
  if (!params.hasOwnProperty('deviceKey') || isEmpty(params['deviceKey'])) {
    params['deviceKey'] = getConfigValue('deviceKey');
  }
  if (!params.hasOwnProperty('userKey') || isEmpty(params['userKey'])) {
    params['userKey'] = getConfigValue('userKey');
    checkUserKey(params['userKey']);
  }
  if (!params.hasOwnProperty('startTime') || !isNumber(params['startTime'])) {
    params['startTime'] = new Date().getTime();
  }
  if (!params.hasOwnProperty('endTime') || !isNumber(params['endTime'])) {
    params['endTime'] = params['startTime'];
  }
  if (isBlank(params['uri'])) {
    params['uri'] = location.href;
  }
  if (isBlank(params['refer'])) {
    if (isBlank(document.referrer)) {
      // span uri here
      params['refer'] = params['uri'];
    } else {
      params['refer'] = document.referrer;
    }
  }
  if (!params.hasOwnProperty('data')) {
    params['data'] = getAllContext();
  } else if (isObject(params['data'])) {
    params['data'] = Object.assign(params['data'], getAllContext());
    if (params['data'].hasOwnProperty('crashInfo')) {
      params['crashInfo'] = params['data']['crashInfo'];
      delete params['data']['crashInfo'];
    }
  } else {
    params['data'] = Object.assign({
      ignore: params['data']
    }, getAllContext());
  }
  if (hooks.length > 0) {
    hooks.forEach(function (hook) {
      if (isFunction(hook)) {
        hook(params);
      }
    });
  }
  var globalHooks = getConfigValue('globalHooks');
  if (Object.keys(globalHooks).length > 0) {
    Object.values(globalHooks).forEach(function (hook) {
      if (isFunction(hook)) {
        hook(params);
      }
    });
  }
  return params;
}

/**
 * using native method to report user log.
 *
 * @param {*} params original report data
 * @param {Array<Function>} hooks report hooks
 * @param {Function} callback callback function when report success
 * @param {*} context callback execution context
 */
function nativeReport() {
  var params = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  var hooks = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
  var callback = arguments.length > 2 ? arguments[2] : undefined;
  var context = arguments.length > 3 ? arguments[3] : undefined;
  generateNativeInvoke('report_event')(generateFullParams(params, hooks), callback, context);
}

/**
 * using xhr method to report user log.
 *
 * @param {*} params original report data
 * @param {Array<Function>} hooks report hooks
 * @param {Function} callback callback function when report finished
 */
function webReport() {
  var params = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  var hooks = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
  var callback = arguments.length > 2 ? arguments[2] : undefined;
  generateWebInvoke(REPORT_API)(generateFullParams(params, hooks), callback);
}
/**
 * using xhr method to report user error log.
 *
 * @param {*} params original report data
 * @param {Array<Function>} hooks report hooks
 * @param {Function} callback callback function when report finished
 */
function webReportError() {
  var params = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  var hooks = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
  var callback = arguments.length > 2 ? arguments[2] : undefined;
  generateWebInvoke(REPORT_ERROR_API)(generateFullParams(params, hooks), callback);
}

/**
 * Copyright (c) 2022-2024，云海链控股股份有限公司.
 */

function setAppInfo(namespace, appKey) {
  var appVersion = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '0.0.1';
  checkNamespace(namespace);
  checkAppKey(appKey);
  setConfigValue('namespace', namespace);
  setConfigValue('appKey', appKey);
  setConfigValue('appVersion', appVersion);
  setContextValue('appVersion', appVersion);
  setContextValue('deviceName', navigator.sayswho);
}
function setDeviceInfo(deviceKey) {
  setConfigValue('deviceKey', deviceKey);
}
function setUserInfo(userKey, clientId, subscribeId) {
  if (isBlank(userKey)) {
    var userKeyCache = getCookie('_user_key_');
    if (isBlank(userKeyCache)) {
      var anonymousUserKey = generateGuid();
      setCookie('_user_key_', anonymousUserKey, 30 * 24);
      setCookie('_anonymous_user_key_', anonymousUserKey, 60 * 24);
    }
    userKey = getCookie('_user_key_');
  } else {
    var _anonymousUserKey = getCookie('_anonymous_user_key_');
    if (!isBlank(_anonymousUserKey)) {
      setContextValue('anonymousUserKey', _anonymousUserKey);
      setCookie('_anonymous_user_key_', _anonymousUserKey, 1);
    }
  }
  setConfigValue('userKey', userKey);
  setConfigValue('clientId', clientId);
  setContextValue('userKey', userKey);
  setContextValue('clientId', clientId);
  setConfigValue('subscribeId', subscribeId);
}

// eslint-disable-next-line no-unused-vars
function setNativeProxyMode() {
  var enable = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
  var overrideField = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
  setConfigValue('enableProxy', enable);
}
function setFreeRouteMode() {
  var enable = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
  var placeholder = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'NULL';
  var includeParams = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
  var excludeParams = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : [];
  setConfigValue('enableFreeRoute', enable);
  setConfigValue('freeRouteIncludeParams', includeParams);
  setConfigValue('freeRouteExcludeParams', excludeParams);
  setConfigValue('freeRoutePlaceholder', placeholder);
}
function startContinuesReport(eventKey) {
  var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
  var interval = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 3;
  var times = 0;
  return setInterval(function () {
    webReport({
      eventKey: eventKey,
      data: {
        offset: offset - offset % interval + times * interval
      }
    });
    times++;
  }, interval * 1000);
}
function stopContinuesReport(reportId) {
  clearInterval(reportId);
}
function reportExt(eventKey) {
  var meta = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  var data = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  var includeParams = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : [];
  var excludeParams = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : [];
  var hooks = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : [];
  checkEventKey(eventKey);
  var hookCallbacks = [];
  if (getConfigValue('enableFreeRoute')) {
    includeParams = isArray(includeParams) && includeParams.length !== 0 ? includeParams : getConfigValue('freeRouteIncludeParams');
    excludeParams = isArray(excludeParams) && excludeParams.length !== 0 ? excludeParams : getConfigValue('freeRouteExcludeParams');
    if (isArray(includeParams) && includeParams.length > 0) {
      var routeParams = [];
      if (isArray(excludeParams) && excludeParams.length > 0) {
        includeParams.forEach(function (param) {
          if (excludeParams.indexOf(param) === -1) {
            routeParams.push(param);
          }
        });
      } else {
        routeParams.push.apply(routeParams, _toConsumableArray(includeParams));
      }
      if (routeParams.length > 0) {
        hookCallbacks.push(function (params) {
          ['uri', 'refer'].forEach(function (key) {
            var queryParams = parseQueryParams(params[key]);
            var routeUri = parseUri(params[key]);
            routeParams.forEach(function (routeParam) {
              if (queryParams.hasOwnProperty(routeParam)) {
                routeUri += "/".concat(routeParam, "/").concat(isBlank(queryParams[routeParam]) ? getConfigValue('freeRoutePlaceholder') : queryParams[routeParam]);
              }
            });
            params[key] = routeUri;
          });
        });
      }
    }
  }
  if (isArray(hooks) && hooks.length > 0) {
    hooks.forEach(function (hook) {
      if (getConfigValue('hooks').hasOwnProperty(hook)) {
        hookCallbacks.push(getConfigValue('hooks')[hook]);
      }
    });
  }
  if (data.hasOwnProperty('crashInfo')) {
    webReportError(_objectSpread(_objectSpread({
      eventKey: eventKey
    }, meta), {}, {
      data: data
    }), hookCallbacks);
    return;
  }
  if (getConfigValue('enableProxy')) {
    nativeReport(_objectSpread(_objectSpread({
      eventKey: eventKey
    }, meta), {}, {
      data: data
    }), hookCallbacks);
  } else {
    webReport(_objectSpread(_objectSpread({
      eventKey: eventKey
    }, meta), {}, {
      data: data
    }), hookCallbacks);
  }
}
function report(eventKey) {
  var data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  reportExt(eventKey, {}, data, [], [], []);
}
function reportError(eventKey) {
  var data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  reportExt(eventKey, {}, data, [], [], []);
}
function addHook(key, callback) {
  var isGlobal = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
  checkHookKey(key);
  checkCallback(callback);
  if (isGlobal) {
    getConfigValue('globalHooks')[key] = callback;
  } else {
    getConfigValue('hooks')[key] = callback;
  }
}
function removeHook(key) {
  checkHookKey(key, true);
  if (getConfigValue('globalHooks').hasOwnProperty('key')) {
    delete getConfigValue('globalHooks')[key];
  }
  if (getConfigValue('hooks').hasOwnProperty('key')) {
    delete getConfigValue('hooks')[key];
  }
}
function bootstrapMpa() {
  var startTime = Date.now();
  window.onbeforeunload = function () {
    reportExt('_VIEW', {
      startTime: startTime,
      endTime: Date.now()
    });
  };
  if (navigator.sayswhere === 2) {
    window.addEventListener('pagehide', function () {
      reportExt('_VIEW', {
        startTime: startTime,
        endTime: Date.now()
      });
    });
  }
}
function bootstrapSpaVue(router) {
  var MAX_HISTORY_STACK_SIZE = 128;
  var BASE_URL = location.href.endsWith('/') ? location.href.substring(0, location.href.length - 1) : location.href;
  // init(as well as clean)
  sessionStorage.setItem('_sdk_history_', JSON.stringify([]));
  router.beforeEach(function (to, from, next) {
    var history = JSON.parse(sessionStorage.getItem('_sdk_history_'));
    if (history.length > 0) {
      var latestRoute = history[0];
      var referRoute = latestRoute;
      if (history.length > 1) {
        referRoute = history[1];
      }
      reportExt('_VIEW', {
        refer: referRoute.route,
        uri: latestRoute.route,
        startTime: latestRoute.startTime,
        endTime: Date.now()
      }, {}, []);
    }
    if (history.length > MAX_HISTORY_STACK_SIZE - 1) {
      history = history.splice(0, MAX_HISTORY_STACK_SIZE - 1);
    }
    history.unshift({
      route: BASE_URL + (to.fullPath.startsWith('/') ? to.fullPath : "/".concat(to.fullPath)),
      startTime: Date.now()
    });
    sessionStorage.setItem('_sdk_history_', JSON.stringify(history));
    next();
  });
}
function bootstrapSpaReact() {
  console.warn('spa-react bootstrap is not supported yet, please listen to route-event manually');
}
function init(config) {
  checkConfig(config);
  var namespace = config.namespace,
    appKey = config.appKey,
    appVersion = config.appVersion,
    deviceKey = config.deviceKey,
    userKey = config.userKey,
    clientId = config.clientId,
    subscribeId = config.subscribeId,
    _config$enableProxy = config.enableProxy,
    enableProxy = _config$enableProxy === void 0 ? false : _config$enableProxy,
    _config$hooks = config.hooks,
    hooks = _config$hooks === void 0 ? {} : _config$hooks,
    _config$bootstrap = config.bootstrap,
    bootstrap = _config$bootstrap === void 0 ? bootstrapMpa : _config$bootstrap,
    _config$bootstrapPara = config.bootstrapParams,
    bootstrapParams = _config$bootstrapPara === void 0 ? {} : _config$bootstrapPara;
  setAppInfo(namespace, appKey, appVersion);
  setDeviceInfo(deviceKey);
  setUserInfo(userKey, clientId, subscribeId);
  setNativeProxyMode(enableProxy);
  if (isObject(hooks) && Object.keys(hooks) > 0) {
    Object.entries(hooks).forEach(function (hook) {
      if (isFunction(hook[1])) {
        addHook(hook[0], hook[1]);
      }
    });
  }
  bootstrap(bootstrapParams);
}
